﻿using System;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace TendEase
{
    internal static class AssemblyResolver
    {
        public static void RedirectAssembly(string shortName, string publicKeyToken)
        {
            var targetVersion = Assembly.Load(shortName).GetName().Version;

            ResolveEventHandler handler = null;

            handler = (sender, args) =>
            {
                // Use latest strong name & version when trying to load SDK assemblies
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.Name != shortName)
                    return null;

                var alreadyLoadedAssembly = AppDomain.CurrentDomain.GetAssemblies()
                    .FirstOrDefault(a => a.GetName().Name == requestedAssembly.Name);

                if (alreadyLoadedAssembly != null)
                    return alreadyLoadedAssembly;

                requestedAssembly.Version = targetVersion;
                requestedAssembly.SetPublicKeyToken(new AssemblyName("x, PublicKeyToken=" + publicKeyToken).GetPublicKeyToken());
                requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;

                AppDomain.CurrentDomain.AssemblyResolve -= handler;

                return Assembly.Load(requestedAssembly);
            };
            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }

        public static void SetResolver()
        {
            RedirectAssembly("Newtonsoft.Json", "30ad4fe6b2a6aeed");
        }
    }
}